package com.snpic.appaw.module.third.service.jpush;

import com.alibaba.fastjson.JSON;
import com.snpic.appaw.module.third.api.jpush.dto.LoginTokenVerifyReqDTO;
import com.snpic.appaw.module.third.api.jpush.dto.LoginTokenVerifyRespDTO;
import com.snpic.appaw.module.third.config.JPushConfig;
import com.snpic.appaw.module.third.service.httpclient.HttpClientServerImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.index.qual.SameLen;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static com.snpic.appaw.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.snpic.appaw.module.third.enums.ErrorCodeConstants.JPUSH_INTERFACE_CALL_EXCEPTION;
import static com.snpic.appaw.module.third.enums.ErrorCodeConstants.SMS_SEND_FAILED;

/**
 * @author JiJun
 * @date 2025/9/9 17:09
 * @修改时间 2025/9/9 17:09
 * @description
 */
@Service
@Slf4j
public class JPushServiceImpl implements JPushService {
	@Resource
	private HttpClientServerImpl httpClientServer;

	@Resource
	private JPushConfig jPushConfig;

	/**
	 * 极光一键登录,H5端
	 *
	 * @param reqDTO 认证SDK获取到的 loginToken
	 * @return 手机号码
	 */
	@Override
	public LoginTokenVerifyRespDTO loginTokenVerify_H5(LoginTokenVerifyReqDTO reqDTO) {
		// 1. 校验参数
		// 2. 调用极光一键登录接口
		String url = jPushConfig.getLoginTokenVerify().getUrlH5();

		// 构建Basic认证头（示例中的账号密码需要替换为实际值）
		String auth = Base64.getEncoder().encodeToString((jPushConfig.getAppKey() + ":" + jPushConfig.getMasterSecret()).getBytes());
		Map<String, String> headers = new HashMap<>();
		headers.put("Authorization", "Basic " + auth);

		String response = null;
		// 2. 调用极光一键登录接口
		try {
			response = httpClientServer.doPostJson(url, reqDTO, headers, "极光安全认证", "一键登录_H5");
		} catch (HttpClientServerImpl.HttpClientException e) {
			log.error("第三发接口调用失败,极光安全认证,一键登录_H5", e);
      throw exception(JPUSH_INTERFACE_CALL_EXCEPTION);
		}

		// 3. 解析返回结果
		LoginTokenVerifyRespDTO respDTO = JSON.parseObject(response, LoginTokenVerifyRespDTO.class);
		if(respDTO != null && respDTO.getCode() == 0){
			// 4. 解密手机号码（需要添加私钥参数）
			// 需要从配置获取privateKey私钥
			try {
				respDTO.setPhone(decrypt(respDTO.getPhone(), jPushConfig.getLoginTokenVerify().getPrivateKeyWeb()));
			} catch (Exception e) {
				throw new RuntimeException("解密手机号失败", e);
			}
		}else{
			throw exception(JPUSH_INTERFACE_CALL_EXCEPTION);
		}
		// 5. 返回结果,0-请求成功
		return respDTO;
	}

	/**
	 *
	 * @param cryptograph  加密后的手机号码
	 * @param prikey 私钥
	 * @return
	 * @throws Exception
	 */
	public String decrypt(String cryptograph, String prikey) throws Exception {
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(prikey));
		PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);

		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		byte[] b = Base64.getDecoder().decode(cryptograph);
		return new String(cipher.doFinal(b));
	}
}
